package com.coolingme.web.handler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.coolingme.domain.entity.SecurityUser;
import com.coolingme.domain.entity.UserInfo;
import com.coolingme.domain.param.JWTParam;
import com.coolingme.domain.vo.LoginInfoVo;
import com.coolingme.util.JWTUtil;
import com.coolingme.util.ResponseUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * AuthenticationSuccessHandler 登录验证成功
 * 
 * @author wangyue
 * @date 2020-03-13 23:53:21
 */
@Component
public class GoAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	/**
	 * Authentication 是封装的用户信息
	 */
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		response.setHeader("Content-Type", "application/json;charset=utf-8");
		SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();

		UserInfo userInfo = new UserInfo().selectOne(Wrappers.lambdaQuery(UserInfo.class)
				.select(UserInfo::getNickName, UserInfo::getWeixinName, UserInfo::getIntegral)
				.eq(UserInfo::getUserId, securityUser.getId()));

//		String token = JWTUtil.createToken(new JWTParam(securityUser, 1000L * 60 * 3));
		String token = JWTUtil.createToken(new JWTParam(securityUser));
		// 设置用户登录信息
		LoginInfoVo loginInfoVo = new LoginInfoVo();
		loginInfoVo.setMessage("success");
		loginInfoVo.setToken(token);
		loginInfoVo.setUserName(securityUser.getUserName());
		loginInfoVo.setPhone(securityUser.getPhone());
		loginInfoVo.setMail(securityUser.getMail());

		loginInfoVo.setNickName(userInfo.getNickName());
		loginInfoVo.setIntegral(userInfo.getIntegral());
		loginInfoVo.setWeixinName(userInfo.getWeixinName());

		String result = ResponseUtil.success(loginInfoVo);
		response.getWriter().write(result);
		response.getWriter().flush();
	}

}
